﻿using System;
using System.Diagnostics;
using System.Text.RegularExpressions;
using System.Collections.Generic;
using System.Text;
using System.Net.Sockets;
using System.IO;
using System.Net;
using System.Threading;
using MySql.Data.MySqlClient;
using System.Configuration;
using System.ComponentModel;
using System.Data.SqlClient;

namespace WordsMatching
{
   public class Scripts
    {
        static TcpListener server;
        const int connections = 1;
        // Declare Private data here 
       const int max = 8500;
      public float[] semantic_score =new float[max] ;
      public  float[] syntactic_score = new float[max];
      int[] map = new int[max];
    public    int[] lev_distance = new int[max];
       string target_string;
     public    string[] trigger_text=new string[max];
       public int trigger_limit = 0;
        string[] response_text=new string[max];
        int response_limit = 0;
        string[] speech = new string[max];
        string[] response_map_id = new string[max];
                int response_map_id_limit = 0;
        string[] trigger_map_id = new string[max];
                int trigger_map_id_limit = 0;
        
        string[][] response_token=new string[max][];
                int [] response_stringLength=new int[max];
        string[][] trigger_token=new string[max][];
                int[] trigger_stringLength=new int [max];
          public      string ServerResponseString = "server reply will be here";
                float ServerResponseScore;
                int ServerOnline = 0;
        string[] source;
        int TriggerLength;
        string server_response;
        float[] response_score = new float[max];
      public  float[] trigger_score = new float[max];
        int speech_response_limit = 0;
        float [][]classifier=new float[max][];
       float []avg=new float [max];
       float SEI;
       int search_depth = 2;
       int Classifier = 0;
       string[] context = new string[max];
       string context_trigger;
        float best_trigger_score, best_response_score;
        Wnlib.PartsOfSpeech[] POSEnum = (Wnlib.PartsOfSpeech[])Enum.GetValues(typeof(Wnlib.PartsOfSpeech));
            HierarchicalWordData[][][] response_wordData_1 = new HierarchicalWordData[max][][];
            HierarchicalWordData[][][] trigger_wordData_1=new HierarchicalWordData[max][][];
            HierarchicalWordData[][] wordData_2=new HierarchicalWordData[50][];
            public string script_trigger="c://scripts/model/test_trigger.txt";
            public string script_response="c://scripts/model/test_response.txt";
            public string script_response_map_id="c://scripts/breast_exam/response_id.txt";
            public string script_trigger_map_id="c://scripts/dysp_id.txt";
            public string speech_responses = "c://scripts/breast_exam/speech.txt";
            public string context_file = "c://scripts/breast_exam/context.txt";
            int context_limit = 0;
            float context_response_score = 0;
            int last_match_pos = 0;
            float last_match_score = 0;
            int iamcontext = 0;


            public void GetSpeechResponses()
            {

                StreamReader S;
                speech_response_limit = 0;
                S = File.OpenText(speech_responses);
                speech[speech_response_limit] = S.ReadLine();
                while (speech[speech_response_limit] != null)
                {

                    speech_response_limit = speech_response_limit + 1;
                    speech[speech_response_limit] = S.ReadLine();
                }

                S.Close();//close the file
                StreamReader c;
                c = File.OpenText(context_file);
                context[context_limit] = c.ReadLine();
                while (context[context_limit] != null)
                {
                    context_limit = context_limit + 1;
                    context[context_limit] = c.ReadLine();
                }
                c.Close();
                if (context_limit != speech_response_limit)
                {
                    System.Console.WriteLine("Error in context text and speech text");
                }
            }
            public void Get_context_response(string input)
            {
                iamcontext = 1;
                context_trigger = string.Concat(input, context[last_match_pos]);
                Get_Target_String_Data(context_trigger);
                Get_Score_Response();
                iamcontext = 0;
            }

            public void Build_Response_Script_Data()
            {
                response_limit = 0;
                response_map_id_limit = 0;

                MySqlConnection myConnection = new MySqlConnection("user id=root;" +
                                       "password=;server=localhost; database=vel;Port=3306");
               
                try
                {



                    myConnection.Open();
                    MySqlCommand myCommand = new MySqlCommand("select response_id,response_text from animesh_response_sentences", myConnection);
                    MySqlDataReader Reader = myCommand.ExecuteReader();



                    while (Reader.Read())
                    {

                        // Console.WriteLine(Reader.GetValue(i).ToString());
                       response_text[response_limit] = Reader.GetString(1);
                        response_map_id[response_map_id_limit] = Reader.GetString(0);
                        response_map_id_limit++;
                        response_limit++;


                    }
                    Reader.Close();
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.ToString());
                }
                myConnection.Close();

            }

       public void Build_Response_Script_Data_file () // use this function when responses are to be retrieved from a file
            {
                StreamReader SR;
                response_limit = 0;
                SR = File.OpenText(script_response);
                response_text[response_limit] = SR.ReadLine();
                while (response_text[response_limit] != null)
                {

                    response_limit = response_limit + 1;
                    response_text[response_limit] = SR.ReadLine();
                }

                SR.Close();//close the file
                //response_limit = response_limit - 1;
                //-----------------------------------------------------
                /*
                response_map_id_limit = 0;
                SR = File.OpenText(script_response_map_id);
                response_map_id[response_map_id_limit] = SR.ReadLine();
                while (response_map_id[response_map_id_limit] != null)
                {

                    response_map_id_limit = response_map_id_limit + 1;
                    response_map_id[response_map_id_limit] = SR.ReadLine();
                }

                SR.Close();//close the file
                //response_map_id_limit = response_map_id_limit - 1;
                if (response_map_id_limit != response_limit)
                {
                    System.Console.WriteLine("\n response text and response id do not match");
                }*/
                //------------------------------------------------------------------------------
            }
       

       public void Build_trigger_script_Data() // Connection to remote database required for this function
       {
           MySqlConnection myConnection = new MySqlConnection("user id=root;" +
                                       "password=;server=localhost; database=vel;Port=3306");
           trigger_limit = 0;
           trigger_map_id_limit = 0;
           try
           {



               myConnection.Open();
               MySqlCommand myCommand = new MySqlCommand("select trigger_id,trigger_text from animesh_trigger_sentences", myConnection);
               MySqlDataReader Reader = myCommand.ExecuteReader();



               while (Reader.Read())
               {
                  
                       // Console.WriteLine(Reader.GetValue(i).ToString());
                      trigger_text [trigger_limit] = Reader.GetString(1);
                        trigger_map_id[trigger_map_id_limit]=Reader.GetString(0);
                        trigger_map_id_limit++;
                        trigger_limit++;
                   

               }
               Reader.Close();
           }
           catch (Exception e)
           {
               Console.WriteLine(e.ToString());
           }
           myConnection.Close();
       }



       public void Build_trigger_script_Data_file()  //Use this function when input is from a file
        {
            StreamReader S;
            trigger_limit = 0;
            S = File.OpenText(script_trigger);
            trigger_text[trigger_limit] = S.ReadLine();
           
            while (trigger_text[trigger_limit] != null)
            {

                trigger_limit = trigger_limit + 1;
                trigger_text[trigger_limit] = S.ReadLine();
               
            }

            S.Close();//close the file

            for (int i = 0; i < trigger_limit; i++)
            {
                lev_distance[i] = -1;
                semantic_score[i] = 0;
                syntactic_score[i] = 0;
            }
            //trigger_limit = trigger_limit - 1;
            //------------------------------------------------------
            
           /*
           trigger_map_id_limit = 0;
            S = File.OpenText(script_trigger_map_id);
            trigger_map_id[trigger_map_id_limit] = S.ReadLine();
            map[trigger_map_id_limit] = trigger_map_id_limit;
            while (trigger_map_id[trigger_map_id_limit] != null)
            {

                trigger_map_id_limit = trigger_map_id_limit + 1;
                trigger_map_id[trigger_map_id_limit] = S.ReadLine();
                map[trigger_map_id_limit] = trigger_map_id_limit;
               
            }

            S.Close();//close the file
            //trigger_map_id_limit = trigger_map_id_limit - 1;
            if (trigger_map_id_limit != trigger_limit)
            {
                System.Console.WriteLine("\n Trigger text and trigger id do not match");
            }*/
            //------------------------------------------------------------------------
           
        }

       public void Build_Response_Search_Data()
        {
            Tokeniser tok = new Tokeniser();
            tok.UseStemming = false;

            for (int i = 0; i < response_limit; i++)
            {
                Console.Write("Loading responses %%done = " + i / (double)response_limit * 100.0 + "\r");
                response_token[i]=tok.Partition(response_text[i]) ;
                response_stringLength[i] = response_token[i].Length;  // string length is m or n
                response_wordData_1[i] = new HierarchicalWordData[response_stringLength[i]][];
                for (int j = 0; j < response_stringLength[i]; j++)
                {
                    response_wordData_1[i][j] = new HierarchicalWordData[POSEnum.Length];
                }

                for (int z = 0; z < response_stringLength[i]; z++)
                {
                    for (int partOfSpeech = 1; partOfSpeech < POSEnum.Length; partOfSpeech++)
                    {
                        if (response_wordData_1[i][z][partOfSpeech] == null)
                        {
                            MyWordInfo myWordsInfo_i = new MyWordInfo(response_token[i][z], POSEnum[partOfSpeech]);
                            response_wordData_1[i][z][partOfSpeech] = new HierarchicalWordData(myWordsInfo_i);
                        }
                    }
                
                }
            }
        }

        public void Build_Trigger_Search_Data( )
        {
            Tokeniser tok = new Tokeniser();
            tok.UseStemming = false;

            for (int i = 0; i < trigger_limit; i++)
            {
                Console.Write("Loading triggers %%done = " + i / (double)trigger_limit * 100.0 + "\r");
                trigger_token[i] = tok.Partition(trigger_text[i]);
                trigger_stringLength[i] = trigger_token[i].Length;  // string length is m or n
                trigger_wordData_1[i] = new HierarchicalWordData[trigger_stringLength[i]][];
                for (int j = 0; j < trigger_stringLength[i]; j++)
                {
                    trigger_wordData_1[i][j] = new HierarchicalWordData[POSEnum.Length];
                }

                for (int z = 0; z < trigger_stringLength[i]; z++)
                {
                    for (int partOfSpeech = 1; partOfSpeech < POSEnum.Length; partOfSpeech++)
                    {
                        if (trigger_wordData_1[i][z][partOfSpeech] == null)
                        {
                            MyWordInfo myWordsInfo_i = new MyWordInfo(trigger_token[i][z], POSEnum[partOfSpeech]);
                            trigger_wordData_1[i][z][partOfSpeech] = new HierarchicalWordData(myWordsInfo_i);
                        }
                    }

                }
            }

        }


        public void Get_Target_String_Data(string trigger)
        {
            target_string = trigger;
            Tokeniser tok = new Tokeniser();
            tok.UseStemming = false;
            source=tok.Partition(trigger);
            TriggerLength=source.Length;

            for ( int j = 0; j < TriggerLength; j++)
                {
                    wordData_2[j] = new HierarchicalWordData[POSEnum.Length];
                }

                for (  int z = 0; z < TriggerLength; z++)
                {
                    for (  int partOfSpeech = 1; partOfSpeech < POSEnum.Length; partOfSpeech++)
                    {
                        if (wordData_2[z][partOfSpeech] == null)
                        {
                            MyWordInfo myWordsInfo_i = new MyWordInfo(source[z], POSEnum[partOfSpeech]);
                            wordData_2[z][partOfSpeech] = new HierarchicalWordData(myWordsInfo_i);
                        }
                    }
                
                }
        }

        public void Get_Similarity_Scores(int option)
        {
            if (option == 1)
            {
                
                Get_Score_Trigger();
            }
            if (option == 2)
            {
                
                Get_Score_Response();
            }
            if (option == 0)
            {
                Get_Score_Trigger();
                Get_Score_Response();
            }
        }

        public void Get_Score_Response()
        {
            for (int counter = 0; counter < response_limit; counter++)
            {
                if (response_stringLength[counter] == 0 || TriggerLength == 0)
                {
                    response_score[counter] = 0F;
                }

                else
                {
                    float[][] simMatrix = new float[response_stringLength[counter]][];

                    for (int i = 0; i < response_stringLength[counter]; i++)
                    {
                        simMatrix[i] = new float[TriggerLength];
                    }
                    for (int i = 0; i < response_stringLength[counter]; i++)
                    {
                        for (int j = 0; j < TriggerLength; j++)
                        {
                            float synDist = AcronymChecker.GetEditDistanceSimilarity(response_token[counter][i], source[j]);

                            for (int partOfSpeech = 1; partOfSpeech < POSEnum.Length; partOfSpeech++)
                            {

                                WordSimilarity wordDistance = new WordSimilarity();
                                float semDist = wordDistance.GetSimilarity(response_wordData_1[counter][i][partOfSpeech], wordData_2[j][partOfSpeech]);
                                float weight = Math.Max(synDist, semDist);
                               /* if (1 == 1)
                                {
                                    weight = semDist;
                                }*/
                                    if (simMatrix[i][j] < weight)
                                    simMatrix[i][j] = weight;
                            }


                        }//end of coloumn

                    }//end of row 

                    HeuristicMatcher match = new HeuristicMatcher();

                    response_score[counter] = HeuristicMatcher.ComputeSetSimilarity(simMatrix, 1);
                }//end of else

            }//end of counter loop

          /*
                float max = -1;
                int max_index = 0;
                for (int j = 0; j < response_limit; j++)
                {
                    //System.Console.Write("\n score: " + (scores[j]));

                    if (max <= response_score[j])
                    {
                        max_index = j;
                        max = response_score[j];
                    }
                }*/
          
              //  System.Console.WriteLine("\n Max Response score: " + (response_score[max_index]));
            //    best_response_score = response_score[max_index];
              //  server_response = speech[max_index];
               // Console.WriteLine("\n Patient:" + (speech[max_index]));
              
           /* if (last_match_score==0)
                {
                    last_match_score=best_response_score;
                    last_match_pos=max_index;
                }
                else //(last_match_score!=0)
                {
                    if (best_response_score>=last_match_score)
                    {
                        //Console.WriteLine("Relevance without context:" +(last_match_score));
                        //Console.WriteLine("Relevance with Context:" +(best_response_score));
                        Console.WriteLine("\n Patient:" +(speech[max_index]));
                        last_match_score=0;
                    }
                    else
                    {
                         //Console.WriteLine("Relevance with context:" +(best_response_score));
                        //Console.WriteLine("Relevance without Context:" +(last_match_score));
                        Console.WriteLine("\n Patient:" +(speech[last_match_pos]));
                        last_match_score=0;
                    }
                
                }*/
            }
        

        public void Debug_Mode()
        {
            for (int counter = 0; counter < trigger_limit; counter++)
            {
                if (trigger_stringLength[counter] == 0 || TriggerLength == 0)
                {
                    trigger_score[counter] = 0F;
                }

                else
                {
                    float[][] simMatrix = new float[trigger_stringLength[counter]][];

                    for (int i = 0; i < trigger_stringLength[counter]; i++)
                    {
                        simMatrix[i] = new float[TriggerLength];
                    }
                    for (int i = 0; i < trigger_stringLength[counter]; i++)
                    {
                        for (int j = 0; j < TriggerLength; j++)
                        {
                            float synDist = AcronymChecker.GetEditDistanceSimilarity(trigger_token[counter][i], source[j]);

                            for (int partOfSpeech = 1; partOfSpeech < POSEnum.Length; partOfSpeech++)
                            {

                                WordSimilarity wordDistance = new WordSimilarity();
                                float semDist = wordDistance.GetSimilarity(trigger_wordData_1[counter][i][partOfSpeech], wordData_2[j][partOfSpeech]);
                                float weight = Math.Max(synDist, semDist);
                                if (simMatrix[i][j] < weight)
                                    simMatrix[i][j] = weight;
                            }


                        }//end of coloumn

                    }//end of row 

                    HeuristicMatcher match = new HeuristicMatcher();

                    trigger_score[counter] = HeuristicMatcher.ComputeSetSimilarity(simMatrix, 1);
                }//end of else

            }//end of counter loop

            //Sort trigger scores here
            for (int i = 0; i < trigger_limit - 2; i++)
            {
                for (int j = i + 1; j <= trigger_limit - 1; j++)
                {
                    if (trigger_score[i] < trigger_score[j])
                    {
                        float temp = trigger_score[i];
                        trigger_score[i] = trigger_score[j];
                        trigger_score[j] = temp;
                        string tid = trigger_map_id[i];
                        trigger_map_id[i] = trigger_map_id[j];
                        trigger_map_id[j] = tid;

                    }
                }
            }

            for (int i = 0; i < 5; i++)
            {
                System.Console.Write(trigger_score[i]);
                System.Console.Write("--Response--->   " );
                System.Console.WriteLine(response_text[System.Convert.ToInt32(trigger_map_id[i])]);
                System.Console.WriteLine("  ");
            }



        }


       /*uncomment after use
        public void Get_Relevant_Triggers()
        {
            for (int counter = 0; counter < trigger_limit; counter++)
            {
                if (trigger_stringLength[counter] == 0 || TriggerLength == 0)
                {
                    trigger_score[counter] = 0F;
                }

                else
                {
                    float[][] simMatrix = new float[trigger_stringLength[counter]][];

                    for (int i = 0; i < trigger_stringLength[counter]; i++)
                    {
                        simMatrix[i] = new float[TriggerLength];
                    }
                    for (int i = 0; i < trigger_stringLength[counter]; i++)
                    {
                        for (int j = 0; j < TriggerLength; j++)
                        {
                            float synDist = AcronymChecker.GetEditDistanceSimilarity(trigger_token[counter][i], source[j]);

                            for (int partOfSpeech = 1; partOfSpeech < POSEnum.Length; partOfSpeech++)
                            {

                                WordSimilarity wordDistance = new WordSimilarity();
                                float semDist = wordDistance.GetSimilarity(trigger_wordData_1[counter][i][partOfSpeech], wordData_2[j][partOfSpeech]);
                                float weight = Math.Max(synDist, semDist);
                                weight = semDist;
                                if (simMatrix[i][j] < weight)
                                    simMatrix[i][j] = weight;
                            }


                        }//end of coloumn

                    }//end of row 

                    HeuristicMatcher match = new HeuristicMatcher();

                    trigger_score[counter] = HeuristicMatcher.ComputeSetSimilarity(simMatrix, 1);

                }//end of else

            }//end of counter loop

            //Score_Sort(trigger_text, trigger_score, trigger_map_id);

            int max_index = 0;
             
            //int[] res_matches = new int[25];
            //int res_matches_limit = 0;
            for (int i = 0; i < trigger_limit; i++)
            {
                map[i] = trigger_map_id[i];
            }
            map = quick_sort(trigger_score, 0, trigger_limit - 1, map);

            System.Console.WriteLine(" Most relevant trigger:");
            
            for (int z = 0; z <1; z++)
            {
                string t = map[z];
                for (int i = 0; i < trigger_limit; i++)
                {
                    if (t == trigger_map_id[i])
                    {
                        max_index = i;
                        System.Console.Write("Relevance   " + trigger_score[max_index]*100+" % ");
                        Console.WriteLine(trigger_text[max_index]);
                    }
                }
            }

        }
       */
       
       public void Get_Score_Trigger()
        {
            
            for (int counter = 0; counter < trigger_limit; counter++)
            {
                List<Diff> mylist;
                diff_match_patch dmp = new diff_match_patch();
                mylist = dmp.diff_main(target_string,trigger_text[counter]);

                lev_distance[counter] = dmp.diff_levenshtein(mylist);
                
                if (trigger_stringLength[counter] == 0 || TriggerLength == 0)
                {
                    trigger_score[counter] = 0F;
                }

                else
                {
                    float[][] simMatrix = new float[trigger_stringLength[counter]][];

                    for (int i = 0; i < trigger_stringLength[counter]; i++)
                    {
                        simMatrix[i] = new float[TriggerLength];
                    }
                    for (int i = 0; i < trigger_stringLength[counter]; i++)
                    {
                        for (int j = 0; j < TriggerLength; j++)
                        {
                            float synDist = AcronymChecker.GetEditDistanceSimilarity(trigger_token[counter][i], source[j]);
                           
                            for (int partOfSpeech = 1; partOfSpeech < POSEnum.Length; partOfSpeech++)
                            {

                                WordSimilarity wordDistance = new WordSimilarity();
                                float semDist = wordDistance.GetSimilarity(trigger_wordData_1[counter][i][partOfSpeech], wordData_2[j][partOfSpeech]);
                                float weight = Math.Max(synDist, semDist);
                                if (synDist > 0)
                                {
                                    syntactic_score[counter] = synDist;
                                }
                                
                                weight = semDist;
                                if (simMatrix[i][j] < weight)
                                    simMatrix[i][j] = weight;
                            }


                        }//end of coloumn

                    }//end of row 

                    HeuristicMatcher match = new HeuristicMatcher();

                    trigger_score[counter] = HeuristicMatcher.ComputeSetSimilarity(simMatrix, 1);
                    semantic_score[counter] = trigger_score[counter];
                }//end of else

            }//end of counter loop

            //Score_Sort(trigger_text, trigger_score, trigger_map_id);
           /*
            int max_index=0;
           // string[] map = new string[max];
           // int[] res_matches = new int[25];
           // int res_matches_limit = 0;
            float temp_score = 0;
            for (int i = 0; i < trigger_limit; i++)
            {
                if (temp_score < trigger_score[i])
                {
                    temp_score = trigger_score[i];
                    max_index = i;
                }
                //map[i] = i;
            }*/
           
           

          

           StreamWriter s;
             s = File.AppendText("c://scripts/model/learn.txt");

             for (int i = 0; i < trigger_limit; i++)
           {
                 s.Write("\n");
                 s.Write(response_score[i]);


                 s.Write(",");

                 s.Write(syntactic_score[i]);
                 s.Write("," + (semantic_score[i]));

                 s.Write("," + (lev_distance[i]));
                 s.WriteLine(",negative");

             }   
             

             s.Close();


         // map= quick_sort(trigger_score, 0, trigger_limit - 1,map);

          //System.Console.WriteLine("Top Response:");
          /*for (int z = 0; z < search_depth; z++)
          {
              string t = System.Convert.ToString(map[z]);
              for (int i = 0; i < response_limit; i++)
              {
                  if (t == response_map_id[i])
                  {
                      max_index = i;
                      System.Console.WriteLine("Map ID" + (t));
                      res_matches[res_matches_limit] = i;
                      res_matches_limit++;
                  }
              }
          }*/
         // ServerResponseString = response_text[max_index];
         // server_response = response_text[max_index];
          
          //s.Write(response_text[max_index]);
          
       //   System.Console.WriteLine("\n Best Trigger match: " +(trigger_text[max_index])+max_index);
         // System.Console.WriteLine("\n Best Response match: " + (response_text[max_index]));
         // System.Console.WriteLine("\n Levenshtein distance : " + (lev_distance[max_index]));
         //  System.Console.WriteLine("\n Score:" +(trigger_score[max_index]));

            /*
            System.Console.WriteLine("\n Other Responses to consider");
            for (int i = 1; i < res_matches_limit; i++)
            {
                System.Console.Write("\n response:" + (i));
                System.Console.WriteLine(response_text[res_matches[i]]);
            }
            System.Console.WriteLine("\n ****************Result of Trigger matching******************");
            System.Console.Write("\n Patient: ");
            System.Console.WriteLine(response_text[res_matches[0]]);
            ResponseMatch(res_matches,res_matches_limit);
           */
        }
        private void ResponseMatch(int[] matches, int limit)
        {
            float []res_score = new float[30];
            for (int counter = 0; counter < limit; counter++)
            {
                if (response_stringLength[matches[counter]] == 0 || TriggerLength == 0)
                {
                    res_score[counter] = 0F;
                }

                else
                {
                    float[][] simMatrix = new float[response_stringLength[matches[counter]]][];

                    for (int i = 0; i < response_stringLength[matches[counter]]; i++)
                    {
                        simMatrix[i] = new float[TriggerLength];
                    }
                    for (int i = 0; i < response_stringLength[matches[counter]]; i++)
                    {
                        for (int j = 0; j < TriggerLength; j++)
                        {
                            float synDist = AcronymChecker.GetEditDistanceSimilarity(response_token[matches[counter]][i], source[j]);

                            for (int partOfSpeech = 1; partOfSpeech < POSEnum.Length; partOfSpeech++)
                            {

                                WordSimilarity wordDistance = new WordSimilarity();
                                float semDist = wordDistance.GetSimilarity(response_wordData_1[matches[counter]][i][partOfSpeech], wordData_2[j][partOfSpeech]);
                                float weight = Math.Max(synDist, semDist);
                                /* if (1 == 1)
                                 {
                                     weight = semDist;
                                 }*/
                                if (simMatrix[i][j] < weight)
                                    simMatrix[i][j] = weight;
                            }


                        }//end of coloumn

                    }//end of row 

                    HeuristicMatcher match = new HeuristicMatcher();

                    res_score[counter] = HeuristicMatcher.ComputeSetSimilarity(simMatrix, 1);
                }//end of else

            }//end of counter loop

            float max = -1;
            int max_index = 0;
            for (int j = 0; j < limit; j++)
            {
                System.Console.Write("\n score: " + (res_score[j]));

                if (max <= res_score[j])
                {
                    max_index = j;
                    max = res_score[j];
                }
            }
            System.Console.WriteLine("\n Max Response score: " + (res_score[max_index]));
            best_response_score = res_score[max_index];
            Console.WriteLine("\n Patient:" + (response_text[matches[max_index]]));
            int z;
        }



        /* float max = -1;
         int max_index = 0;
         for (int j = 0; j < trigger_limit; j++)
         {
             //System.Console.Write("\n score: " + (scores[j]));

             if (max <= trigger_score[j])
             {
                 max_index = j;
                 max = trigger_score[j];
                  
             }
         }*/














        //best_trigger_score = trigger_score[max_index];
        //System.Console.WriteLine("Best Trigger Match:" + (trigger_text[max_index]));
        // System.Console.WriteLine("Trigger Map ID :" +(trigger_map_id[max_index]));
        /*  int count = 0;
                
          string speech_index;
          int []response_id =new int[50];
          int response_id_end = 0;
          speech_index = trigger_map_id[max_index];
          for (count = 0; count < response_limit; count++)
          {
              if (response_map_id[count] == speech_index)
              {
                  response_id[response_id_end] = count;
                  response_id_end++;
              }
          }

          System.Console.WriteLine("Best Response Matches to consider :" );
                    
      for (int i = 0; i < response_id_end; i++)
          {
                       
          System.Console.WriteLine(response_text[response_id[i]]);
          }
      */


        // ServerResponseScore = trigger_score[max_index];
        /*
             count = 0; ;
                
            response_id = 0;
            speech_index = trigger_map_id[max_index];
            for (count = 0; count < response_limit; count++)
            {
                if (response_map_id[count] == speech_index)
                {
                    response_id = count;
                }
            }*/
        //  ServerResponseString = response_text[response_id];








        /*public void Get_Classifier_Matrix()
        {
            int counter = 0;
            int col = 0;
            int counter2 = 0;
            for (int i = 0; i < response_limit; i++)
            {
                classifier[i] = new float[response_limit];
            }
            while ( counter < response_limit-1)
            {

                col = 0;
                while (col < response_limit)
                {
                    counter2 = counter + 1;

                    float[][] simMatrix = new float[response_stringLength[counter]][];

                    for (int i = 0; i < response_stringLength[counter]; i++)
                    {
                        simMatrix[i] = new float[response_stringLength[counter2]];
                    }


                    for (int i = 0; i < response_stringLength[counter]; i++)
                    {
                        for (int j = 0; j < response_stringLength[counter2]; j++)
                        {
                            float synDist = AcronymChecker.GetEditDistanceSimilarity(response_token[counter][i], response_token[counter2][j]);

                            for (int partOfSpeech = 1; partOfSpeech < POSEnum.Length; partOfSpeech++)
                            {

                                WordSimilarity wordDistance = new WordSimilarity();
                                float semDist = wordDistance.GetSimilarity(response_wordData_1[counter][i][partOfSpeech], response_wordData_1[counter2][j][partOfSpeech]);
                                float weight = Math.Max(synDist, semDist);
                                if (simMatrix[i][j] < weight)
                                    simMatrix[i][j] = weight;
                            }


                        }//end of coloumn

                    }//end of row 

                    HeuristicMatcher match = new HeuristicMatcher();

                    classifier[counter][counter2] = HeuristicMatcher.ComputeSetSimilarity(simMatrix, 1);
                    classifier[counter2][counter] = classifier[counter][counter2];

                    col = col + 1;
                }

                counter = counter + 1;
            }//end of while
        }*/

        /*public void SEI()
        {
            for (int i = 0; i < response_limit; i++)
            {
                for (int j = 0; j < response_limit; j++)
                {
                    System.Console.Write("  " + (classifier[i][j]));
                }
                System.Console.WriteLine(" ");
            }


        }*/
        public void Get_Classifier_Matrix()
        {
            Classifier = 1;
            int counter = 0;
            float avg_sum=0;
            for (int j = 0; j < response_limit; j++) 
            {
                classifier[j] = new float[response_limit];
            }
            
            while (counter < response_limit)
            {
              
                Get_Target_String_Data(response_text[counter]);
                Get_Score_Response();
              
                    for (int j = 0; j < response_limit; j++)
                    {
                        
                        classifier[counter][j] = response_score[j];

                    }
                
                counter = counter + 1;
            }
            
            float[] sum = new float[response_limit];
            for (int i = 0; i < response_limit; i++)
            {
                sum[i] = 0;
            }
            for (int i = 0; i < response_limit; i++)
            {
                for (int j = 0; j < response_limit; j++)
                {
                    sum[i] = classifier[i][j] + sum[i];
                }
               
            }
           for (int i = 0; i < response_limit; i++)
            {
                avg[i]=(sum[i]-1)/(response_limit-1);
               avg_sum=avg[i]+avg_sum;
            }
           SEI=avg_sum/response_limit;
            System.Console.WriteLine("Number of responses" +(response_limit));
            System.Console.WriteLine("SEI :" +(SEI));
        
        }
        public void Enable_Responses()
        {
            Classifier = 0;
        }

       /* public void Classifier_Data()
        {
            float[] avg = new float[500];
            for (int k = 0; k < response_limit; k++)
            {
                avg[k] = 0F;
            }
            for (int i = 0; i < 1; i++)
            {
                for (int j = 0; j < response_limit; j++)
                {
                    System.Console.WriteLine( classifier[i][j]) ;

                }

            }
            float result = avg[0] / response_limit - 1;
            System.Console.WriteLine("Average score for first trigger is" +(result));

        }*/

        public void StartServer()
        {
            try
            {
                IPAddress ipAd = IPAddress.Parse("127.0.0.1"); //use local m/c IP address, and use the same in the client
                TcpListener myList = new TcpListener(ipAd, 8001);

                myList.Start();

                Console.WriteLine("The server is running at port 8001...");
                Console.WriteLine("The local End point is  :" + myList.LocalEndpoint);
                Console.WriteLine("Waiting for a connection.....");
                while (true)
                {
                    Socket s = myList.AcceptSocket();
                    Console.WriteLine("Connection accepted from " + s.RemoteEndPoint);
                    if (s.Connected)
                    {

                        byte[] b = new byte[1000];
                        int k = s.Receive(b);
                        Console.WriteLine("Recieved...");
                        for (int i = 0; i < k; i++)
                            Console.Write(Convert.ToChar(b[i]));
                        System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
                        string teststring = enc.GetString(b);
                        // System.Console.WriteLine(teststring);
                        //teststring is the string that needs to be sent as target string
                       Get_Target_String_Data(teststring);
                       Get_Score_Trigger();
                       // Get_Similarity_Scores(1);
                        ASCIIEncoding asen = new ASCIIEncoding();
                        
                        s.Send(asen.GetBytes(server_response));
                        //Console.WriteLine("\\nSent Acknowledgement");
                    }
                    s.Close();
                }
                myList.Stop();

            }

            catch (Exception e)
            {
                Console.WriteLine("Error..... " + e.StackTrace);
            }
        }

        public void new_server()
        {
            IPEndPoint ip = new IPEndPoint(IPAddress.Any, 8001);
            Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            socket.Bind(ip);
            socket.Listen(10);
            Console.WriteLine("Waiting for a client...");
            Socket client = socket.Accept();
            IPEndPoint clientep = (IPEndPoint)client.RemoteEndPoint;
            Console.WriteLine("Connected with {0} at port {1}", clientep.Address, clientep.Port);

            string welcome = "Welcome";
            byte[] data = new byte[1024];
            data = Encoding.ASCII.GetBytes(welcome);
            



            data = new byte[1024];
            int receivedDataLength = client.Receive(data);
            for (int i = 0; i < receivedDataLength; i++)
                Console.Write(Convert.ToChar(data[i]));
            System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
            string request = enc.GetString(data);

          //  ServerResponseString = "Hi Animesh";
          Get_Target_String_Data(request);
          Get_Score_Trigger();
           // Get_Similarity_Scores(1);
            ASCIIEncoding asen = new ASCIIEncoding();
            client.Send(asen.GetBytes(ServerResponseString));
            //client.Send(data, receivedDataLength, SocketFlags.None);

            //client.Send(data, data.Length, SocketFlags.None);
            Console.WriteLine("\n Waiting for new request........");
            client.Close();
            socket.Close();
        }

       
       
       private int[] quick_sort(float[] arr, int left, int right,int [] sort_trigger_map_id) 
       {
      int i = left, j = right;
      float tmp;
      float pivot = arr[(left + right) / 2];
      int s;
      /* partition */
      while (i <= j) {
            while (arr[i] > pivot)
                  i++;
            while (arr[j]< pivot)
                  j--;
            if (i <= j) {
                  tmp = arr[i];
                  arr[i] = arr[j];
                  arr[j] = tmp;
                    
                  s = sort_trigger_map_id[i];
                  sort_trigger_map_id[i] = sort_trigger_map_id[j];
                  sort_trigger_map_id[j] = s;
                  i++;
                  j--;
            }
      };
 
      /* recursion */
      if (left < j)
            quick_sort(arr, left, j,sort_trigger_map_id);
      if (i < right)
            quick_sort(arr, i, right,sort_trigger_map_id);
      return sort_trigger_map_id;
    }
   
   }//end of class

}// end of namespace